package com.itheima.reggie.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.JwtUtil;
import com.itheima.reggie.ResultInfo;
import com.itheima.reggie.SmsTemplate;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;

    //发送成功
    @Override
    public void sendSms(String phone) {
        //生成6位随机验证码
        //TODO 为了开发测试方便,临时写成固定验证码
       // String code = RandomUtil.randomNumbers(6);

        String code = "123456";
        System.out.println("生成的验证码为："+code);
        //调用redis保存
        redisTemplate.opsForValue().set("CODE_" + phone, code, 5, TimeUnit.MINUTES);

        //调用阿里云发送
        //TODO 开发期间，暂时注释
        //smsTemplate.sendSms(phone, code);
    }


    //登陆注册
    @Override
    public ResultInfo login(String phone, String code) {
        //1.比对验证码，失败返回提示
        String codeRedis = (String) redisTemplate.opsForValue().get("CODE_" + phone);
        if (!StringUtils.equals(code, codeRedis)) {
            return ResultInfo.error("验证码错误！");
        }
        //2.根据手机号查询数据库是否存在
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone);
        User user = userMapper.selectOne(wrapper);
        //判断
        if (user != null) {
            //3.查询到了
            if (user.getStatus() != 1) { //1是正常
                return ResultInfo.error("账号状态异常!");
            }
        } else {
            //4.没有查询到，新注册保存到数据库
            user = new User(); // 这一步缺少会导致空指针
            user.setPhone(phone);
            user.setStatus(1);
            userMapper.insert(user);
        }

        //5.生成token
        HashMap map = new HashMap();
        map.put("id", user.getId());
        map.put("phone", user.getPhone());
        String token = JwtUtil.createToken(map);

        //6.将token保存到redis
        redisTemplate.opsForValue().set("TOKEN_" + token, user, 1, TimeUnit.DAYS);

        //7.返回token
        return ResultInfo.success(token);

    }


    //退出，删除token
    @Override
    public void delete(String token) {
        redisTemplate.delete("TOKEN_" + token);
    }
}
